package main

import (
	//"fmt"
	"fmt"
	"iot-base/common/logger"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/go-ping/ping"
	"github.com/panjf2000/ants/v2"
)

func online(id string, isOnline bool, onLineMap *sync.Map) {
	onLineMap.Store(id, isOnline)
	// if isOnline {
	// 	var alarm eventtype.Alarm
	// 	alarm.TID = id
	// 	alarm.AlarmID = "offline"
	// 	alarm.Flag = "END"
	// 	alarm.Checker = "onlineCheck/tcp/http/ping"
	// 	notify.RawAlarm(&alarm)
	// }
}

func makeFun(id, ip string, mode string, onLineMap *sync.Map) func() {
	if mode == "ping" {
		return func() {
			checkWithPing(id, ip, onLineMap)
		}
	}
	if mode == "tcp" {
		return func() {
			checkWithTCP(id, ip+":80", onLineMap)
		}
	}
	if mode == "http" {
		return func() {
			checkWithHttp(id, "http://"+ip, onLineMap)
		}
	}
	return nil

}

func beginCheck(id, ip string, onLineMap *sync.Map) {
	//fmt.Printf("begin adding running goroutines: %d\n", ants.Running())
	ants.Submit(makeFun(id, ip, confg.CheckMode, onLineMap))
	//fmt.Printf("finish adding running goroutines: %d\n", ants.Running())
	if id == "1122" {
		fmt.Println("****add********1122******")
	}
}
func checkWithTCP(id, ip string, onLineMap *sync.Map) {
	timeout := time.Duration(time.Duration(confg.CheckTimeout) * time.Second)
	//t1 := time.Now()
	conn, err := net.DialTimeout("tcp", ip, timeout)
	//fmt.Println("waist time :", time.Now().Sub(t1))
	if conn != nil {
		defer conn.Close()
	}
	if id == "1122" {
		fmt.Println("************1122******", err, id, ip)
	}
	isOnline := (err == nil)
	online(id, isOnline, onLineMap)
}
func checkWithPing(id, ip string, onLineMap *sync.Map) {
	pinger, err := ping.NewPinger(ip)
	pinger.SetPrivileged(true)
	if err != nil {
		panic(err)
	}
	if id == "1122" {
		fmt.Println("*ping***********1122****begin**")
	}
	pinger.Count = 1
	//pinger.Interval = time.Millisecond * 500
	err = pinger.Run() // Blocks until finished.
	if err != nil {
		//panic(err)
		logger.SLog.Error("ping error", err)
	}
	stats := pinger.Statistics()
	if id == "1122" {
		fmt.Println("*ping***********1122****end**", stats, stats.PacketsRecv)
	}
	isOnline := stats.PacketsRecv > 0
	online(id, isOnline, onLineMap)
}

func checkWithHttp(id, ip string, onLineMap *sync.Map) {
	timeout := time.Duration(confg.CheckTimeout) * time.Second
	client := http.Client{
		Timeout: timeout,
	}
	if id == "1122" {
		fmt.Println("*http***********1122****begin**")
	}
	resp, err := client.Get(ip)
	if id == "1122" {
		fmt.Println("*http***********1122****end**", err, ip)
	}
	if resp != nil {
		defer resp.Body.Close()
	}

	online(id, err == nil, onLineMap)

}

func isOnline(id string, mapOnline *sync.Map) bool {
	online, ok := mapOnline.Load(id)
	if ok {
		isOnlineFromMap := online.(bool)
		return isOnlineFromMap
	}
	return false
}
func init() {
	beginPool()
}

func beginPool() {
	ants.NewPool(100)
}
